<?php
/**
 * 作用：游戏模块
 * 作者: shijy@soe-soe.com
 * 日期: 2016/5/11 16:09
 * 公司: 浙江宣逸网络科技有限公司<www.soe-soe.com>
 */


namespace Common\Model;
use Think\Model\MongoModel;

class GameModel extends BaseModel{
    //提现方式
    const EXTRACT_BANK   = 0;
    const EXTRACT_WEIXIN = 1;
    const EXTRACT_ALIPAY = 2;

    public static function getPayTypeKv(){
        return array(
            self::EXTRACT_BANK      =>'银行卡',
            self::EXTRACT_WEIXIN    =>'微信',
            self::EXTRACT_ALIPAY    =>'支付宝'
        );
    }

    //处理情况
    const PROCESS_UNDO=0;//未处理
    const PROCESS_DONE=1;//已处理


    /**
     * 取游戏键值数组
     * @return array
     */
    public static function getGameKv(){
        return array(
            GAME_FENGHUA   =>'奉化双扣',
            GAME_JIASHAN   =>'嘉善游戏',
            GAME_JINGDE    =>'旌德麻将',
            GAME_XIANGSHAN =>'象山游戏',
            GAME_JINGXIAN  =>'径县麻将',            
            GAME_DAISHAN   =>'岱山',        
        );
    }


    /**
     * 获取游戏概况
     */
    public static function getDash(){
        $m=M('daily_count',null,'manage');
        list($begin,$end)=UtilsModel::getLastDay();
        $yesterday=date('Y-m-d',$begin);
        $where="date = '{$yesterday}'";
        $array = $m->group('date')->where($where)
            ->field('count(1) as gameNum,sum(newUser) as newUser,sum(loginUser) as loginUser,sum(totalUser) as totalUser,sum(totalRecharge) as totalRecharge,sum(rechargeMoney) as rechargeMoney,sum(rechargeUser) as rechargeUser,SUM(consumeDiamond) as consumeDiamond,SUM(room) as room,SUM(game) as game')
            ->find();
        return $array;
    }

    /**
     * 获取代理键值对
     * @param $plat
     * @return array
     */
    public static function getAgentKv($plat){
        $agentM = M('users', null, 'mysql_' . $plat);
        $agentArr = $agentM->where("is_agent=1")
            ->field('id,`name` as realName')
            ->select();
        $kv=array();
        foreach ($agentArr as $one){
            $kv[$one['id']]=$one['realName'];
        }
        unset($agentArr);
        return $kv;
    }

    /**
     * 取代理记录
     * @param $plat 平台
     * @param $agent 代理编号
     * @return array 代理数据
     */
    public static function getAgentArr($plat,$agentId=0){
        $agentM = M('users', null, 'mysql_' . $plat);

        $where="is_agent=1";
        if ($agentId>0){
            $where .=' and id='.$agentId;
        }

        $agentArr = $agentM->where($where)
                ->field('id,`name` as realName,nick_name,phone,agent_level,apply_time,promotion_reward,removed_promotion_reward')
                ->select();
        $agentMap = array();
        foreach ($agentArr as $agent) {
                $agentMap[$agent['id']] = $agent;
        }
        return $agentMap;
    }



    /**
     * 每日统计报表
     */
    public static function dailyCount($plat,$date=null){
        if(!$date){
            $date="yesterday";
        }
        $beginTimestamp=strtotime($date);
        $datestr=date('Y-m-d',$beginTimestamp);

        $endTimestamp=$beginTimestamp+UtilsModel::ONE_DAY;
        $newData=array(
            'gameId'    =>$plat,
            'date'      =>$datestr,
            'totalUser' =>0,
            'totalRecharge'=>0,
            'newUser'   =>0,
            'loginUser' =>0,
            'loginUserPeakHour' =>0,
            'rechargeMoney'     =>0,
            'rechargeUser'      =>0,
            'consumeDiamond'   =>0,
            'room'      =>0,
            'game'      =>0

        );

        //mongo数据库操作
        $mongoUser = new QipaiModel("userinfo", null, 'mongo_'.$plat);
        do {
            //总注册
            $mongoCode = 'db.getCollection("userinfo").count()';
            $re = $mongoUser->mongoCode($mongoCode);
            $newData['totalUser'] = $re;

            //注册
            $mongoCode = 'db.getCollection("userinfo").find({"status.registertimestamp":{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}).count()';
            $re = $mongoUser->mongoCode($mongoCode);
            $newData['newUser'] = $re;


            //登陆人数
            $mongoCode = 'db.getCollection(\'userinfo\').aggregate(
[
{$match:{"status.logintime":/' . $datestr . '.*/}}
,{$project:{\'hour\':{$substr:["$status.logintime",11,2]}}}
,{$group:{"_id":"$hour","num":{$sum:1}}}
,{$sort:{"_id":1}}
]).toArray()';
            $re = $mongoUser->mongoCode($mongoCode);

            $totalLogin = 0;
            $max = 0;
            $maxHour = '';
            foreach ($re as $hour) {
                $totalLogin += (int)$hour['num'];
                if ($hour['num'] > $max) {
                    $max = $hour['num'];
                    $maxHour = $hour['_id'];
                }
            }
            $newData['loginUser'] = $totalLogin;
            $newData['loginUserPeakHour'] = $max;


            //消耗钻石
            $mongoCode = 'db.getCollection("newItemsHistory").aggregate([{$match:{"itemid":2,"diff":{$lt:0},"timestamp":{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"1","diamond":{$sum:"$diff"}}}]).toArray()';
            $re = $mongoUser->mongoCode($mongoCode);
            $newData['consumeDiamond'] = abs($re[0]['diamond']);


            //总开房，总局数
            $mongoCode = 'db.getCollection(\'globalroomdata\').aggregate([{$match:{\'createtime\':{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":1,"times":{$sum:"$curgamenbr"},"room":{$sum:1}}}]).toArray()';
            $re = $mongoUser->mongoCode($mongoCode);
            //echo '总开房，总局数';
            //pre_dump($re);
            $newData['room'] = $re[0]['room'];
            $newData['game'] = $re[0]['times'];

        }while(false);

        //mysql统计
        $orderM=M('orders',null,'mysql_'.$plat);
        do {
            $rechargeArr = $orderM->where(" order_status=4 and date(create_time)='$datestr'")
                ->field("count(distinct user_id) as users,sum(summary_diamond_quantity) as rechargeDiamond,sum(summary_cost) as rechargeMoney")
                ->find();
            $newData['rechargeMoney']=$rechargeArr['rechargeMoney']/100;
            $newData['rechargeUser']=$rechargeArr['users'];

            //总充值金额
            $rechargeArr = $orderM->where("order_status=4")
                ->field("sum(summary_cost) as rechargeMoney")
                ->find();
            $newData['totalRecharge']=$rechargeArr['rechargeMoney']/100;
        }while(false);

        //pre_dump($newData);
        M('daily_count',null,'manage')->add($newData,null,true);

    }


    /**
     * 每月统计报表
     */
    public static function monthlyCount($plat){
        list($beginTimestamp,$endTimestamp)=UtilsModel::getLastMonth();

        $beginDateStr   = date('Y-m-d',$beginTimestamp);
        $endDateStr     = date('Y-m-d',$endTimestamp);

        $datestr        = date('Ym',$beginTimestamp);
        $newData=array(
            'gameId'            =>$plat,
            'month'             =>$datestr,
            'newUser'           =>0,
            'loginUser'         =>0,
            'rechargeMoney'     =>0,
            'rechargeUser'      =>0,
            'rechargeTimes'     =>0,
            'consumeDiamond'    =>0,
            'room'              =>0,
            'game'              =>0
        );

        $mongoUser = new QipaiModel("userinfo", null, 'mongo_'.$plat);
        do {
            //注册
            $mongoCode = 'db.getCollection("userinfo").find({"status.registertimestamp":{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}).count()';
            $re = $mongoUser->mongoCode($mongoCode);
            $newData['newUser'] = $re;


            //登陆人数
            $mongoCode = 'db.getCollection(\'userinfo\').aggregate(
[
{$match:{"status.logintimestamp":{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}}
,{$group:{"_id":"1","num":{$sum:1}}}
]).toArray()';
            $re = $mongoUser->mongoCode($mongoCode);

            $newData['loginUser'] = $re[0]['num'];



            //消耗钻石
            $mongoCode = 'db.getCollection("newItemsHistory").aggregate([{$match:{"itemid":2,"diff":{$lt:0},"timestamp":{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"1","diamond":{$sum:"$diff"}}}]).toArray()';
            $re = $mongoUser->mongoCode($mongoCode);
            $newData['consumeDiamond'] = abs($re[0]['diamond']);


            //总开房，总局数
            $mongoCode = 'db.getCollection(\'globalroomdata\').aggregate([{$match:{\'createtime\':{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":1,"times":{$sum:"$curgamenbr"},"room":{$sum:1}}}]).toArray()';
            $re = $mongoUser->mongoCode($mongoCode);
            //echo '总开房，总局数';
            //pre_dump($re);
            $newData['room'] = $re[0]['room'];
            $newData['game'] = $re[0]['times'];

        }while(false);

        $orderM=M('orders',null,'mysql_'.$plat);
        do {
            $rechargeArr = $orderM->where(" order_status=4 and create_time between '{$beginDateStr}' and '{$endDateStr}'")
                ->field("count(distinct user_id) as users,sum(summary_diamond_quantity) as rechargeDiamond,sum(summary_cost) as rechargeMoney,count(1) as rechargeTimes")
                ->find();
            $newData['rechargeMoney']=$rechargeArr['rechargeMoney']/100;
            $newData['rechargeUser']=$rechargeArr['users'];
            $newData['rechargeTimes']=$rechargeArr['rechargeTimes'];
        }while(false);

        M('monthly_count',null,'manage')->add($newData,null,true);

    }

    /**
     * 获取日统计
     * @param $gameId
     * @param $beginDate
     * @param $endDate
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function getDailyCount($gameId,$beginDate,$endDate,$page=1,$pageSize=31){
        $m=M('daily_count',null,'manage');
        $where='1';
        if ($beginDate){
            $where.=" and `date`>='{$beginDate}'";
        }
        if ($endDate){
            $where.=" and `date`<='{$endDate}'";
        }
        $offset=max($page-1,0)*$pageSize;
        if ($gameId){
            $recordCount=$m->where("gameId='{$gameId}' and {$where}")->count();
            $array = $m->where("gameId='{$gameId}' and {$where}")->order("gameid asc,date desc")->limit($offset,$pageSize)->select();
        }else {
            //SELECT date,sum(newUser),sum(loginUser),sum(rechargeMoney),sum(rechargeUser),SUM(consumeDiamond),SUM(room),SUM(game),count(1) FROM `daily_count` GROUP BY date order by date desc;
            $recordCount= $m->where($where)->count("distinct date");
            $array = $m->group('date')->where($where)
                ->field('\'全部\' as gameId,date,sum(newUser) as newUser,sum(loginUser) as loginUser,sum(loginUserPeakHour) as loginUserPeakHour,sum(rechargeMoney) as rechargeMoney,sum(rechargeUser) as rechargeUser,SUM(consumeDiamond) as consumeDiamond,SUM(room) as room,SUM(game) as game')
                ->order("date desc")->limit($offset,$pageSize)->select();
        }
        $pageCount=ceil($recordCount/$pageSize);

        return array('data'=>$array,'pageSize'=>$pageSize,'recordCount'=>$recordCount,'page'=>$page,'pageCount'=>$pageCount);

    }

    /**
     * 获取月统计
     * @param $gameId
     * @param $beginDate
     * @param $endDate
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function getMonthlyCount($gameId,$beginDate,$endDate,$page=1,$pageSize=31){
        $m=M('monthly_count',null,'manage');
        $where='1';
        if ($beginDate){
            $where.=" and `month`>='{$beginDate}'";
        }
        if ($endDate){
            $where.=" and `month`<='{$endDate}'";
        }
        $offset=max($page-1,0)*$pageSize;
        if ($gameId){
            $recordCount=$m->where("gameId='{$gameId}' and {$where}")->count();
            $array = $m->where("gameId='{$gameId}' and {$where}")->order("gameid asc,month desc")->limit($offset,$pageSize)->select();
        }else {
            //SELECT date,sum(newUser),sum(loginUser),sum(rechargeMoney),sum(rechargeUser),SUM(consumeDiamond),SUM(room),SUM(game),count(1) FROM `daily_count` GROUP BY date order by date desc;
            $recordCount= $m->where($where)->count("distinct month");
            $array = $m->group('month')->where($where)
                ->field('\'全部\' as gameId,month,sum(newUser) as newUser,sum(loginUser) as loginUser,sum(rechargeTimes) as rechargeTimes,sum(rechargeMoney) as rechargeMoney,sum(rechargeUser) as rechargeUser,SUM(consumeDiamond) as consumeDiamond,SUM(room) as room,SUM(game) as game')
                ->order("month desc")->limit($offset,$pageSize)->select();
        }
        $pageCount=ceil($recordCount/$pageSize);

        return array('data'=>$array,'pageSize'=>$pageSize,'recordCount'=>$recordCount,'page'=>$page,'pageCount'=>$pageCount);

    }


    /**
     * 代理分润
     * @param $plat
     * @param $endTimestamp 截止时间戳
     * @param $agentId
     * @return array
     */
    public static function agentBenefit($plat,$agentId,$endTimestamp=0)
    {
        //取代理
        do {
            $agentMap = self::getAgentArr($plat,$agentId);
            $agentId = array();
            foreach ($agentMap as $userId=>$one) {
                $agentMap[$userId]['directBenefit'] = 0;//直接
                $agentMap[$userId]['indirectBenefit'] = 0;//间接分润
                $agentMap[$userId]['rechargeMoney'] = 0;//充值金额
                $agentMap[$userId]['paid'] = 0;//已结算金额
                $agentMap[$userId]['unpaid'] = 0;//未结算金额
                $agentMap[$userId]['payAccount'] = '';//结算账户

                $agentId[] = $userId;
            }
        }while(false);


        //下级代理 agentChild
//        $agentChildM=M('agent_child',null,'mysql_'.$plat);
//        $childArr=$agentChildM->field('user_id,child_user_id')->select();
//        foreach ($childArr as $one){
//            if(!array_key_exists($one['child_user_id'],$agentMap)){
//                continue;
//            }
//            $agentMap[$one['child_user_id']]['parent']=$one['user_id'];
//        }


        //直接分成，间接分成   promotion_share_money_record
        do {
            $benefitM = M('promotion_share_money_record', null, 'mysql_' . $plat);
            $benefitArr = $benefitM->where('`status`=1')
                ->group('parent_id,level')
                ->field('parent_id as agentId,level,sum(profit_share_money)/100 as benefit')
                ->select();

            foreach ($benefitArr as $one) {
                if (!array_key_exists($one['agentId'], $agentMap)) {
                    continue;
                }
                if ($one['level'] == 1) {
                    $agentMap[$one['agentId']]['directBenefit'] += $one['benefit'];//直接分润
                } else {
                    $agentMap[$one['agentId']]['indirectBenefit'] += $one['benefit'];//间接分润
                }


            }
        }while(false);



        //取玩家与代理关系user_child_join
        do {
            $userM  = M('user_child_join',null,'mysql_'.$plat);
            $childs = $userM->where('user_id in ('.implode(',',$agentId).") and status=1")
                ->field('user_id,child_user_id')
                ->select();

            $userMap=array();
            foreach($childs as $child){
                $userMap[$child['child_user_id']+0]=$child['user_id']+0;
            }
        }while(false);

        //直接下级充值
        do {
            $orderM = M('orders', null, 'mysql_' . $plat);
            $rechargeArr = $orderM->where("order_status=4")
                ->group("user_id")
                ->field("user_id,sum(summary_diamond_quantity) as rechargeDiamond,sum(summary_cost) as rechargeMoney")
                ->select();

            foreach ($rechargeArr as $one) {
                $uid = $one['user_id'] + 0;
                if (!array_key_exists($uid, $userMap)) {
                    continue;
                }
                $agentId = $userMap[$uid];
                if (!array_key_exists($agentId, $agentMap)) {
                    continue;
                }
                $agentMap[$agentId]['rechargeMoney'] += $one['rechargeMoney'];
            }
        }while(false);

        ///提现，结算
        do {
            $where="status=1";
            if ($endTimestamp>0)
            {
                $endtimestr=date('Y-m-d H:i:s',$endTimestamp);
                $where.=" and create_time <='{$endtimestr}'";
            }
            $extractM = M('promotion_extract_apply', null, 'mysql_' . $plat);
            $extractArr = $extractM->where($where)
                ->group("user_id,apply_status")
                ->field("user_id,apply_status,bank_card_id,sum(amount)/100 as money")
                ->select();

            foreach ($extractArr as $one) {
                $agentId = $one['user_id'];
                if (!array_key_exists($agentId, $agentMap)) {
                    continue;
                }
                switch ($one['apply_status'] + 0) {
                    case self::PROCESS_DONE:
                        $agentMap[$agentId]['paid'] += $one['money'];
                        break;
                    case self::PROCESS_UNDO:
                        $agentMap[$agentId]['unpaid'] += $one['money'];
                        break;
                }
                $agentMap[$agentId]['payAccount'] = $one['bank_card_id'];
            }
        }while(false);

        //结算记录处理
//        do {
//            $payM = M('agent_pay', null, 'manage');
//            $paidArr = $payM->where("gameId='{$plat}'")
//                ->group('agentId')
//                ->field('agentId,sum(money) as paidMoney')
//                ->select();
//
//            foreach ($paidArr as $one) {
//                $agentId = $one['agentId'];
//                if (!array_key_exists($agentId, $agentMap)) {
//                    continue;
//                }
//                $agentMap[$agentId]['paid'] += $one['paidMoney'];
//                $agentMap[$agentId]['unpaid'] -= $one['paidMoney'];
//            }
//        }while(false);



        //SELECT user_id,bank_card_id,sum(amount)/100 FROM `promotion_extract_apply` where apply_status=0 and status=1 group by user_id;


        return $agentMap;

    }


    /**
     * @param $plat  游戏
     * @param $agentId 代理编号
     * @param $money 结算金额,单位:元
     */
    public static function agentBenefitProcess($plat,$agentId,$money,$operatorId){
        $money *=100;
        $data=array('status'=>0,'msg'=>'success');
        $extractM = M('promotion_extract_apply', null, 'mysql_' . $plat);
        $extractArr = $extractM->where(" status=1 and apply_status=0 and user_id={$agentId}")
            ->field("amount,id")
            ->order('id asc')
            ->select();
        $ids=array();
        $sum=0;
        foreach ($extractArr as $one){
            if($sum<$money){
                $sum+=$one['amount'];
                $ids[]=$one['id'];
            }elseif($sum == $money){
                //刚刚好
                break;
            }else{
                return array('status'=>1,'msg'=>'结算金额不符');
            }
        }
        if($sum!=$money){
            return array('status'=>1,'msg'=>'结算金额不符');
        }

        $timestr=date('Y-m-d H:i:s',time());
        $update=array('apply_status'=>self::PROCESS_DONE,"update_time"=>$timestr);

        $idstr=implode(',',$ids);
        M('promotion_extract_apply',null,'outer_'.$plat)
            ->where("id in ({$idstr})")
            ->setField($update);

        M('promotion_extract_apply',null,'mysql_'.$plat)
            ->where("id in ({$idstr})")
            ->setField($update);


        M('agent_pay',null,'manage')->add(array(
            'gameId'=>$plat,
            'agentId'=>$agentId,
            'money'=>$money,
            'addtime'=>time(),
            'operator'=>$operatorId
        ));

        $log=array();
        foreach ($ids as $id){
            $log[]=array(
                'game'=>$plat,
                'orignID'=>$id,
                'addtime'=>$timestr
            );
        }
        M('extract_log',null,'manage')->addAll($log);


        return array('status'=>0,'msg'=>'成功');

    }

    /**
     * 代理结算记录添加
     * @param $gameId   string 游戏
     * @param $agentId int
     * @param $money
     * @param $operatorId
     */
    public static function addAgetnPayLog($gameId,$agentId,$money,$operatorId){

    }


    /**
     * 
     * @param $agentId
     */
    public static function getAgentExtractLog($agentId,$plat){
        $extractM = M('promotion_extract_apply', null, 'mysql_' . $plat);
        $extractArr = $extractM->where("status=1 and user_id={$agentId}")
            ->field("user_id,type,apply_status,bank_card_id,amount/100 as money,create_time")
            ->order("id desc")
            ->select();
        return $extractArr;
    }


    /**
     * 下级代理业绩查询
     * @param $plat
     */
    public static function getLowerAgentstat($plat){

        //取全部代理
        do {
            $agentMap = self::getAgentArr($plat);
            $agentId  = array();
            foreach ($agentMap as $userId=>$one) {
                $agentMap[$userId]['child'] = array();
                $agentMap[$userId]['rechargeMoney'] = 0;//直接级充值金额
                $agentMap[$userId]['giveParent'] = 0;//给直接上家的贡献值
                $agentMap[$userId]['rate'] = 0;//给直接上家的贡献值

                $agentId[] = $userId;
            }
        }while(false);


        //代理上下级映射 agentChild
        $levelMap=array();
        do {
            $agentChildM = M('agent_child', null, 'mysql_' . $plat);
            $childArr = $agentChildM->field('user_id,child_user_id')->select();
            foreach ($childArr as $one) {
                $levelMap[$one['child_user_id']]=$one['user_id'];//子 > 父
            }
        }while(false);



        //取玩家与代理关系   user_child_join
        do {
            $userM  = M('user_child_join',null,'mysql_'.$plat);
            $childs = $userM->where('user_id in ('.implode(',',$agentId).") ")
                ->field('user_id,child_user_id')
                ->select();

            $userMap=array();
            foreach($childs as $child){
                $userMap[$child['child_user_id']+0]=$child['user_id']+0;
            }
        }while(false);


        //子代理分成贡献值记录   promotion_share_money_record
        do {
            $benefitM = M('promotion_share_money_record', null, 'mysql_' . $plat);
            $benefitArr = $benefitM->where('`status`=1 and `level`=2' )
                ->group('child_id')
                ->field('parent_id as agentId,child_id,sum(profit_share_money)/100 as benefit,profit_share_rate as rate')
                ->select();


            foreach ($benefitArr as $one) {
                $childId=(int)$one['child_id'];
                if (!array_key_exists($childId, $userMap)) {
                    echo 'undo';
                    pre_dump($one);
                    continue;
                }

                $fatherAgent=$userMap[$childId];
                if (!array_key_exists($fatherAgent, $agentMap)) {
                    continue;
                }

                $agentMap[$fatherAgent]['giveParent']+=$one['benefit'];//给上家贡献值累加
                $agentMap[$fatherAgent]['rate']=$one['rate'];//给上家贡献值累加
            }
        }while(false);



        //直接下级充值
        do {
            $benefitM = M('promotion_share_money_record', null, 'mysql_' . $plat);
            $rechargeArr = $benefitM->where('`status`=1 and `level`=1' )
                ->group('parent_id')
                ->field('parent_id as agentId,sum(money)/100 as rechargeMoney')
                ->select();

            foreach ($rechargeArr as $one) {
                $agentId = $one['agentId'] + 0;
                if (!array_key_exists($agentId, $agentMap)) {
                    continue;
                }
                $agentMap[$agentId]['rechargeMoney'] = intval($one['rechargeMoney']);
            }
        }while(false);


        //组装上下级代理
        do{
            foreach ($levelMap as $sonID=>$fatherID){
                if(!array_key_exists($fatherID,$agentMap)){
                    continue;
                }
                if(!array_key_exists($sonID,$agentMap)){
                    continue;
                }
                $agentMap[$fatherID]['child'][]=array(
                    'id'            => $sonID,
                    'realName'      => $agentMap[$sonID]['realName'],
                    'rechargeMoney' => $agentMap[$sonID]['rechargeMoney'],
                    'rate'          => $agentMap[$sonID]['rate'],
                    'benefit'       => $agentMap[$sonID]['giveParent']
                );
            }
        }while(false);


        return  $agentMap;
    }


    /**
     * 代理统计
     * @param $plat  平台
     * @param $beginTimestamp  时间戳
     * @param $endTimestamp  时间戳
     * @param $agentId
     * @param $agentName
     * @param $agentLevel
     * @return array
     */
    public static function getAgentCount($plat,$beginTimestamp=0,$endTimestamp=0,$agentId=0,$agentName,$agentLevel){
        //取代理
        $agentMap=self::getAgentArr($plat,$agentId);
        $agentIdArr=array();
        foreach ($agentMap as $agentId=>$one){
            $agentMap[$agentId]['lowerNum']=0;//下级代理数
            $agentMap[$agentId]['userAccount']=0;//绑定玩家数
            $agentMap[$agentId]['rechargeMoney']=0;//玩家充值
            $agentMap[$agentId]['lowerRechargeMoney']=0;//下级代理充值数
            $agentMap[$agentId]['profit']=0;//总返利
            $agentMap[$agentId]['consumeDiamond']=0;//玩家消耗钻石
            $agentMap[$agentId]['stockDiamond']=0;//玩家库存钻石
            $agentMap[$agentId]['room']=0;//开房数
            $agentIdArr[]=$agentId;
        }



        $m=M('agent_child',null,'mysql_'.$plat);

        $where='1';
        if($beginTimestamp>0){
            $beginTimeStr=date('Y-m-d H:i:s',$beginTimestamp);
            $where .=" and create_time >='{$beginTimeStr}'";
        }

        if($endTimestamp>0){
            $endTimeStr=date('Y-m-d H:i:s',$endTimestamp);
            $where .= " and create_time <'{$endTimeStr}'";
        }else{
            $endTimestamp=PHP_INT_MAX;
        }

        //下级代理数
        do {
            $lowerArr = $m->where($where)->group("user_id")
                ->field('user_id,count(child_user_id) as lowerNum')
                ->select();
            foreach($lowerArr as $one){
                $agentId=intval($one['user_id']);
                if(!array_key_exists($agentId,$agentMap)){
                    continue;
                }
                $agentMap[$agentId]['lowerNum']=$one['lowerNum'];
            }
        }while(false);

        //下级代理充值金额
        do{
            $m=M('promotion_share_money_record',null,'mysql_'.$plat);
            $ids=implode(',',$agentIdArr);
            $recharges=$m->where($where." and parent_id in ({$ids}) and status=1")
                ->group('parent_id,level')
                ->field("parent_id,level,sum(money)/100 as rechargeMoney,sum(profit_share_money)/100 as profit")
                ->select();

            foreach($recharges as $one){
                $agentId=intval($one['parent_id']);
                if(!array_key_exists($agentId,$agentMap)){
                    continue;
                }
                if ($one['level']==1){
                    $agentMap[$agentId]['rechargeMoney']=floatval($one['rechargeMoney']);
                }else{
                    $agentMap[$agentId]['lowerRechargeMoney'] +=floatval($one['rechargeMoney']);
                }
                $agentMap[$agentId]['profit'] +=floatval($one['profit']);



            }
        }while(false);

        //直接玩家人数
        do{
            $userAgentMap=array();
            $userIDs=array();
            $m=M('user_child_join',null,'mysql_'.$plat);
            $userCount=$m->where($where." and user_id in ({$ids})  and status=1")
                ->field('user_id,child_user_id')
                ->select();
            foreach ($userCount as $one){
                $agentId=intval($one['user_id']);
                if(!array_key_exists($agentId,$agentMap)){
                    continue;
                }
                $agentMap[$agentId]['userAccount'] += 1;
                $userAgentMap[$one['child_user_id']] = $one['user_id'];

                $userIDs[]=intval($one['child_user_id']);

            }
        }while(false);



        $mongoUser = new QipaiModel("userinfo", null, 'mongo_'.$plat);
        //直接用户消耗
        do {
            $uidStr = implode(',', $userIDs);
            $mongoCode = 'db.getCollection("newItemsHistory").aggregate([{$match:{"uid":{$in:[' . $uidStr . ']},"itemid":2,"diff":{$lt:0},"timestamp":{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"$uid","diamond":{$sum:"$diff"}}}]).toArray()';

            $re = $mongoUser->mongoCode($mongoCode);
            foreach ($re as $one) {
                $uid = intval($one['_id']);
                if (!array_key_exists($uid, $userAgentMap)) {
                    continue;
                }
                $agentId = $userAgentMap[$uid];
                $agentMap[$agentId]['consumeDiamond'] += abs($one['diamond']);
            }
        }while(false);

        //库存钻石数
        do {
            $m = M('users', null, 'mysql_' . $plat);
            $stockS = $m->where("id in ({$uidStr})")
                ->field('id,diamond_quantity')
                ->select();



            foreach($stockS as $one){
                $uid=intval($one['id']);
                if(!array_key_exists($uid,$userAgentMap)){
                    continue;
                }

                $agentId=$userAgentMap[$uid];
                $agentMap[$agentId]['stockDiamond'] +=abs($one['diamond_quantity']);
            }

        }while(false);

        //总开房
        do {
            $mongoCode = 'db.getCollection(\'globalroomdata\').aggregate([{$match:{\'owner\':{$in:[' . $uidStr . ']},\'createtime\':{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"$owner","room":{$sum:1}}}]).toArray()';
            $re = $mongoUser->mongoCode($mongoCode);
            foreach ($re as $one) {
                $uid = intval($one['_id']);
                if (!array_key_exists($uid, $userAgentMap)) {
                    continue;
                }
                $agentId = $userAgentMap[$uid];
                $agentMap[$agentId]['room'] += $one['room'];
            }
        }while(false);

        return $agentMap;
    }


    /**
     * 取用户详情列表
     * @param $plat
     * @param $agentId
     * @param $beginTimestamp
     * @param $endTimestamp
     * @param int $userid
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function getUserList($plat,$agentId,$beginTimestamp=0,$endTimestamp=0,$userid=0,$page=1,$pageSize=30){

        $page=max($page,1);
        $offset=($page-1)*$pageSize;



        $where = '1';
        if ($agentId>0){//指定代理
            $inWhere = "status=1 and user_id={$agentId}";
            if ($userid>0){
                $inWhere.=" and child_user_id={$userid}";
            }
            $uidArr=M('user_child_join',null,'mysql_'.$plat)
                ->where($inWhere)
                ->getField('child_user_id',true);

            $where .= ' and id in ('.implode(',',$uidArr).')';

        }elseif ($userid>0){
            $where .=" and id={$userid}";
        }


        $userM=M('users',null,'mysql_'.$plat);
        $recordCount=$userM->where($where)->count();
        $userData=$userM->where($where)->field( 'id,nick_name,register_time,phone')->limit($offset,$pageSize)->select();

        $uid=array();
        $userMap=array();
        foreach ($userData as $k=>$v){
            $uid[]=$v['id'];
            $v['room']=0;//开房数
            $v['times']=0;//局数
            $v['rechargeMoney']=0;//充值金额
            $userMap[intval($v['id'])]=$v;
        }

        $dateWhere = '1';
        if($beginTimestamp>0){
            $dateWhere = 'create_time >=\''.date('Y-m-d H:i:s',$beginTimestamp).'\'';
        }


        if($endTimestamp<=0){
            $endTimestamp=time();
        }
        $dateWhere .=' and create_time <=\''.date('Y-m-d H:i:s',$endTimestamp).'\'';


        $uidStr=implode(',',$uid);
        //充值金额
        $orderM = M('orders', null, 'mysql_' . $plat);
        $rechargeArr = $orderM->where("order_status=4 and user_id in ({$uidStr}) and {$dateWhere}")
            ->group("user_id")
            ->field("user_id,sum(summary_cost)/100 as rechargeMoney")
            ->select();
        foreach ($rechargeArr as $one){
            $uid = intval($one['user_id']);
            $userMap[$uid]['rechargeMoney'] = floatval($one['rechargeMoney']);//充值金额
        }

        $mongoUser = new QipaiModel("userinfo", null, 'mongo_'.$plat);

        //游戏内充
        $mongoCode = 'db.getCollection("gameorder").aggregate([{$match:{"bok":1,"uid":{$in:[' . $uidStr . ']},"timestamp":{$gt:'.$beginTimestamp.',$lt:'.$endTimestamp.'}}},{$group:{"_id":"$uid","rmb":{$sum:"$rmb"}}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        foreach ($re as $one){
            $uid = intval($one['_id']);
            $userMap[$uid]['rechargeMoney'] +=$one['rmb'];
        }




        $mongoCode = 'db.getCollection("userinfo").aggregate([{$match:{"uid":{$in:[' . $uidStr . ']}}},{$project:{"_id":"$uid","diamond":"$mahjong.diamond"}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        foreach ($re as $one){
            $uid = intval($one['_id']);
            $userMap[$uid]['diamond_quantity'] =$one['diamond'];
        }

        //消耗钻石
        $mongoCode = 'db.getCollection("newItemsHistory").aggregate([{$match:{"uid":{$in:[' . $uidStr . ']},"itemid":2,"diff":{$lt:0},"timestamp":{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"$uid","diamond":{$sum:"$diff"}}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        foreach ($re as $one){
            $uid = intval($one['_id']);
            $userMap[$uid]['consumeDiamond'] =abs($one['diamond']);
        }


        //开房数，3，6，9
        $mongoCode = 'db.getCollection(\'globalroomdata\').aggregate([{$match:{\'owner\':{$in:[' . $uidStr . ']},\'createtime\':{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":{"user":"$owner","round":"$basegamenbr"},"room":{$sum:1}}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        foreach ($re as $one){
            $uid = intval($one['_id']['user']);
            $round = intval($one['_id']['round']);
            $userMap[$uid]['room']  +=$one['room'];
            $userMap[$uid]['round_'.$round]  =$one['room'];
        }



        //参与牌局数，1
        $mongoCode = 'db.getCollection(\'globalroomdata\').aggregate([{$match:{\'history.statistics.1.uid\':{$in:[' . $uidStr . ']},\'createtime\':{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"$history.statistics.1.uid","times":{$sum:"$curgamenbr"},}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        foreach ($re as $one){
            $uid = intval($one['_id']);
            $userMap[$uid]['times']  +=$one['times'];
        }
        //参与牌局数，2
        $mongoCode = 'db.getCollection(\'globalroomdata\').aggregate([{$match:{\'history.statistics.2.uid\':{$in:[' . $uidStr . ']},\'createtime\':{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"$history.statistics.2.uid","times":{$sum:"$curgamenbr"},}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        foreach ($re as $one){
            $uid = intval($one['_id']);
            $userMap[$uid]['times']  +=$one['times'];
        }
        //参与牌局数，3
        $mongoCode = 'db.getCollection(\'globalroomdata\').aggregate([{$match:{\'history.statistics.3.uid\':{$in:[' . $uidStr . ']},\'createtime\':{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"$history.statistics.3.uid","times":{$sum:"$curgamenbr"},}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        foreach ($re as $one){
            $uid = intval($one['_id']);
            $userMap[$uid]['times']  +=$one['times'];
        }
        //参与牌局数，4
        $mongoCode = 'db.getCollection(\'globalroomdata\').aggregate([{$match:{\'history.statistics.4.uid\':{$in:[' . $uidStr . ']},\'createtime\':{$gte:' . $beginTimestamp . ',$lte:' . $endTimestamp . '}}},{$group:{"_id":"$history.statistics.4.uid","times":{$sum:"$curgamenbr"},}}]).toArray()';
        $re = $mongoUser->mongoCode($mongoCode);
        foreach ($re as $one){
            $uid = intval($one['_id']);
            $userMap[$uid]['times']  +=$one['times'];
        }


        $agentArr=M('user_child_join',null,'mysql_'.$plat)->where("status=1 and child_user_id in ({$uidStr})")
            ->select();
        $agentKV=self::getAgentKv($plat);
        foreach ($agentArr as $one){
            $agentId=intval($one['user_id']);
            $uid=intval($one['child_user_id']);

            $userMap[$uid]['agent']=$agentKV[$agentId];
            $userMap[$uid]['agentId']=$agentId;
            $userMap[$uid]['agentDateStr']=$one['create_time'];
        }

        $pageCount=ceil($recordCount/$pageSize);
        return array('data'=>$userMap,'pageSize'=>$pageSize,'recordCount'=>$recordCount,'page'=>$page,'pageCount'=>$pageCount);

    }


    /**
     * 导出用户全部数据
     * @param $plat
     * @param $agentId
     * @param int $beginTimestamp
     * @param int $endTimestamp
     * @param int $userid
     * @return array|mixed
     */
    public static function exportUserListAll($plat,$agentId,$beginTimestamp=0,$endTimestamp=0,$userid=0){
        set_time_limit(0);
        ini_set('memory_limit','500M');

        $ret=self::getUserList($plat,$agentId,$beginTimestamp,$endTimestamp,$userid,1,100);
        $list=$ret['data'];
        for($page=2;$page<=$ret['pageCount'];$page++){
            $other=self::getUserList($plat,$agentId,$beginTimestamp,$endTimestamp,$userid,$page,100);
            $list=array_merge($list,$other['data']);
        }



        $data=array();
        foreach ($list as $item){
            $data[]=array(
        $item['id'],$item['nick_name'],$item['register_time'],$item['phone'],$item['agent'],$item['agentDateStr'],$item['rechargeMoney'],$item['consumeDiamond'],$item['diamond_quantity'],$item['times'],$item['room'],$item['round_3'],$item['round_6'],$item['round_9']
            );
        }
        $title=array('用户ID','用户昵称','注册时间','绑定手机号','代理','被绑定时间','充值金额','消耗钻石','剩余钻石','参与牌局数','开房总数','3局开房数','6局开房数','9局开房数' );



        CommonModel::exportExcel_saveas($data,$title,'user_data');
    }




}